package com.zliblike_platform.service.impl;

import com.zliblike_platform.dto.BookListDTO;
import com.zliblike_platform.dto.BookListItemDTO;
import com.zliblike_platform.entity.BookList;
import com.zliblike_platform.entity.BookListItem;
import com.zliblike_platform.mapper.BookListItemMapper;
import com.zliblike_platform.mapper.BookListMapper;
import com.zliblike_platform.mapper.BookMapper;
import com.zliblike_platform.service.BookListService;
import com.zliblike_platform.vo.BookListItemVO;
import com.zliblike_platform.vo.BookListVO;
import com.zliblike_platform.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 书单服务实现类
 */
@Service
public class BookListServiceImpl implements BookListService {

    @Autowired
    private BookListMapper bookListMapper;
    
    @Autowired
    private BookListItemMapper bookListItemMapper;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Override
    @Transactional
    public Long createBookList(Long userId, BookListDTO bookListDTO) {
        // 创建书单实体
        BookList bookList = new BookList();
        bookList.setTitle(bookListDTO.getTitle());
        bookList.setDescription(bookListDTO.getDescription());
        bookList.setCreatorId(userId);
        bookList.setIsPublic(bookListDTO.getIsPublic());
        bookList.setBookCount(0);
        
        Date now = new Date();
        bookList.setCreatedAt(now);
        bookList.setUpdatedAt(now);
        
        // 插入数据库
        bookListMapper.insert(bookList);
        
        return bookList.getListId();
    }
    
    @Override
    @Transactional
    public boolean updateBookList(Long userId, Long listId, BookListDTO bookListDTO) {
        // 查询书单
        BookListVO existingList = bookListMapper.selectById(listId);
        if (existingList == null || !existingList.getCreatorId().equals(userId)) {
            return false;
        }
        
        // 更新书单
        BookList bookList = new BookList();
        bookList.setListId(listId);
        bookList.setTitle(bookListDTO.getTitle());
        bookList.setDescription(bookListDTO.getDescription());
        bookList.setIsPublic(bookListDTO.getIsPublic());
        bookList.setUpdatedAt(new Date());
        
        return bookListMapper.update(bookList) > 0;
    }
    
    @Override
    public BookListVO getBookListDetail(Long listId, Long userId) {
        // 查询书单详情
        BookListVO bookList = bookListMapper.selectById(listId);
        if (bookList == null) {
            return null;
        }
        
        // 如果书单不是公开的，并且当前用户不是创建者，则无权查看
        if (!bookList.getIsPublic() && !bookList.getCreatorId().equals(userId)) {
            return null;
        }
        
        // 判断当前用户是否可以编辑该书单
        boolean canEdit = bookList.getCreatorId().equals(userId);
        bookList.setCanEdit(canEdit);
        
        return bookList;
    }
    
    @Override
    public List<BookListItemVO> getBookListItems(Long listId) {
        // 查询书单详情
        BookListVO bookList = bookListMapper.selectById(listId);
        if (bookList == null) {
            return null;
        }
        
        // 查询书单中的书籍
        return bookListItemMapper.selectByListId(listId);
    }
    
    @Override
    @Transactional
    public Long addBookToList(Long userId, Long listId, BookListItemDTO itemDTO) {
        // 查询书单
        BookListVO bookList = bookListMapper.selectById(listId);
        if (bookList == null || !bookList.getCreatorId().equals(userId)) {
            return null;
        }
        
        // 检查书籍是否存在
        if (bookMapper.selectById(itemDTO.getBookId()) == null) {
            return null;
        }
        
        // 检查书籍是否已在书单中
        if (bookListItemMapper.existsInList(listId, itemDTO.getBookId())) {
            return null;
        }
        
        // 创建书单条目
        BookListItem item = new BookListItem();
        item.setListId(listId);
        item.setBookId(itemDTO.getBookId());
        item.setNote(itemDTO.getNote());
        
        Date now = new Date();
        item.setAddedAt(now);
        item.setUpdatedAt(now);
        
        // 插入数据库
        bookListItemMapper.insert(item);
        
        // 更新书单中的书籍数量
        bookListMapper.updateBookCount(listId);
        
        return item.getItemId();
    }
    
    @Override
    @Transactional
    public boolean removeBookFromList(Long userId, Long listId, Long itemId) {
        // 查询书单
        BookListVO bookList = bookListMapper.selectById(listId);
        if (bookList == null || !bookList.getCreatorId().equals(userId)) {
            return false;
        }
        
        // 删除书单条目
        boolean result = bookListItemMapper.deleteById(itemId, listId) > 0;
        
        // 更新书单中的书籍数量
        if (result) {
            bookListMapper.updateBookCount(listId);
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public boolean updateBookNote(Long userId, Long listId, Long itemId, String note) {
        // 查询书单
        BookListVO bookList = bookListMapper.selectById(listId);
        if (bookList == null || !bookList.getCreatorId().equals(userId)) {
            return false;
        }
        
        // 查询书单条目
        BookListItemVO item = bookListItemMapper.selectById(itemId);
        if (item == null) {
            return false;
        }
        
        // 更新书单条目
        BookListItem updatedItem = new BookListItem();
        updatedItem.setItemId(itemId);
        updatedItem.setNote(note);
        updatedItem.setUpdatedAt(new Date());
        
        return bookListItemMapper.update(updatedItem) > 0;
    }
    
    @Override
    public PageResult<BookListVO> getPublicBookLists(Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        
        // 查询总记录数
        Integer total = bookListMapper.countPublic();
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / size);
        
        // 查询记录
        List<BookListVO> records = bookListMapper.selectPublicWithPagination(offset, size);
        
        return new PageResult<>(total, totalPages, page, records);
    }
    
    @Override
    public PageResult<BookListVO> getUserBookLists(Long userId, Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        
        // 查询总记录数
        Integer total = bookListMapper.countByUserId(userId);
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / size);
        
        // 查询记录
        List<BookListVO> records = bookListMapper.selectByUserIdWithPagination(userId, offset, size);
        
        return new PageResult<>(total, totalPages, page, records);
    }
    
    @Override
    @Transactional
    public boolean deleteBookList(Long userId, Long listId) {
        // 删除书单中的所有书籍
        bookListItemMapper.deleteByListId(listId);
        
        // 删除书单
        return bookListMapper.deleteById(listId, userId) > 0;
    }

    @Override
    public boolean favoriteBookList(Integer userId, Integer listId) {
        return false;
    }

    @Override
    public boolean unfavoriteBookList(Integer userId, Integer listId) {
        return false;
    }

    @Override
    public boolean isBookListFavorited(Integer userId, Integer listId) {
        return false;
    }

    @Override
    public int getBookListFavoriteCount(Integer listId) {
        return 0;
    }

    @Override
    public List<BookListVO> getUserFavoriteBookLists(Integer userId, int page, int size) {
        return null;
    }
} 